package filter

import (
	"yikexing.com.cn/wyws/bus"
	"yikexing.com.cn/wyws/models"

	"errors"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
)

func init() {
	beego.InsertFilter("/v1/*", beego.BeforeRouter, UserFilter)

}

const SessionIdName = "sessionId"

// 获取用户的sesionId,
func UserFilter(ctx *context.Context) {
	sessionId := ctx.Input.Query(SessionIdName)
	//如果不为空, 先看看这个sessionId在当前session中是否存在. 如果不存在就去获取.
	if sessionId == "" {
		//应该将他打到特定的地方去.
		beego.Error("Can not found SessionId")
		CustomAbort(ctx, 401, "401")
		return
	}
	userSessionInfo := models.UserSessionInfo{SessionId: sessionId}
	err := bus.Dispatch(&userSessionInfo)
	if err != nil {
		//应该将他打到特定的地方去.
		CustomAbort(ctx, 401, "401")
		return
	}
	beego.Info(fmt.Sprintf("the session id is: %s", sessionId))
}

func CustomAbort(ctx *context.Context, status int, body string) {
	if _, ok := beego.ErrorMaps[body]; ok {
		ctx.Output.Status = status
		panic(body)
	}
	ctx.ResponseWriter.WriteHeader(status)
	ctx.ResponseWriter.Write([]byte(body))
	panic(errors.New("User stop run"))
}
